package com.yuchengtech.simpleServer.core.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.util.HashMap;

import com.yuchengtech.fileUtil.FileUtil;
import com.yuchengtech.simpleServer.core.Http;
import com.yuchengtech.simpleServer.core.HttpRequest;
import com.yuchengtech.simpleServer.core.HttpResponse;
import com.yuchengtech.simpleServer.core.SimpleHttpServer;
import com.yuchengtech.simpleServer.core.exception.SimpleServerException;
import com.yuchengtech.simpleServer.servlet.FileServlet;
import com.yuchengtech.simpleServer.servlet.SimpleServlet;

/**
 * This class is to handle reading the request file and send data to the browser.
 *@author David zhang
 *@since Tue 24 May 2011
 *@version 1.0
 */
public class FileHandler implements Handler{

	
	private static final FileHandler fileHandler=new FileHandler();
	public static final HashMap<String, String> mimeMap=new HashMap<String, String>();
	
	static{
		
		//图片类
		mimeMap.put("jpg","image/jpeg");
		mimeMap.put("jpeg","image/jpeg");
		mimeMap.put("png","image/jpeg");
		mimeMap.put("gif","image/gif");
		mimeMap.put("bmp","image/bmp");
		mimeMap.put("ico","image/x-icon");
		mimeMap.put("ief","image/ief");
			
		//资源类
		mimeMap.put("js","application/x-javascript");
		mimeMap.put("css","text/css");
		mimeMap.put("txt","text/plain");
		
		//音频类
		mimeMap.put("mp2","video/mpeg");
		mimeMap.put("mp3","video/mpeg");
		mimeMap.put("mpeg","video/mpeg");
		mimeMap.put("mpg","video/mpeg");
		mimeMap.put("wav","audio/x-wav");
		mimeMap.put("mid","audio/mid");
		mimeMap.put("au","audio/basic");
			
		
		//视频类
		mimeMap.put("avi","video/x-msvideo");
		mimeMap.put("mov","video/quicktime");
		mimeMap.put("swf","application/x-shockwave-flash");
		mimeMap.put("mov","video/quicktime");
			
		//应用程序	
		mimeMap.put("exe","application/octet-stream");
		mimeMap.put("pdf","application/pdf");
		mimeMap.put("pot","application/vnd.ms-powerpoint");
		mimeMap.put("pps","application/vnd.ms-powerpointf");
		mimeMap.put("ppt","application/vnd.ms-powerpoint");
		mimeMap.put("doc","application/msword");
		mimeMap.put("dot","application/msword");
		mimeMap.put("xls","application/vnd.ms-excel");
		mimeMap.put("zip","application/zip");
			
	}
	private FileHandler()
	{}
	
	public void doHandle(Socket connection, HttpRequest request,
			HttpResponse response) {
		
		String url=request.getNowUrl();
		FileInputStream stream=null;
		if(url.length()>0)
		{
			String postFix2=request.getPostfix().toLowerCase();
			String mine=mimeMap.get(postFix2);
			if(mine!=null)
				{
					response.setMimeType(mine);
					if("txt".equals(postFix2)||"html".equals(postFix2)||"htm".equals(postFix2)
							||"css".equals(postFix2)||"js".equals(postFix2))
						;
					else response.setCharset(null);
				}

			String basePath=SimpleHttpServer.getBasePath();
			File file=new File(FileUtil.contactPath(basePath, url));
			if(!file.exists()||file.isDirectory())
				response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
			else if(!file.canRead())
				response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED);
			else 
			{
				
				//缓存控制器
				String eTag=request.getHeaders().get("If-None-Match");
				if(eTag!=null)
				{
						//fix to second
						if(eTag.equals(file.lastModified()+""))
						{
							//304缓存
							response.setStatusCode(HttpURLConnection.HTTP_NOT_MODIFIED);
							response.addHeader("Cache-control","max-age=86400");//缓存1天
							try {
								response.commitResponse();
							} catch (IOException e) {
							}
							System.out.println(url+" not modified!");
							return ;
						}
				}
				
				
				response.addHeader("last-modified",Http.formatTime(file.lastModified()));
				response.addHeader("Cache-control","max-age=86400");//缓存1天
				response.addHeader("ETag", file.lastModified()+"");
				try {
					stream=new FileInputStream(file);
					SimpleServlet servlet=new FileServlet(stream,file.length());
					try {
						servlet.service(request, response);
					} catch (SimpleServerException e) {
						e.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
					e.printStackTrace();
				}
			}
		}
		
		try {
			if(response.getStatusCode()!=200)
			{
				System.out.println(request.getUrl()+" not found!");
			}
			response.doResponse();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			if(stream!=null)
					stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
  public static FileHandler getSingleHandler()
  {
	return fileHandler;
  }
}
